<template>
  <!--新增、编辑 、查看 共用-->
  <div class="sms-add">
    <h3 class="notice-title">{{ noticeId ? '编辑通知' : '添加通知' }}</h3>
    <el-form
      :model="formModel"
      :rules="formRules"
      ref="formModel"
      label-width="100px"
    >
      <el-row :gutter="20" type="flex" justify="space-start">
        <el-col :span="9">
          <el-form-item label="企业名称" prop="toCompanyName">
            <el-select
              class="input-width"
              v-model="formModel.toCompanyName"
              filterable
              clearable
              remote
              placeholder="请输入"
              :remote-method="getEnterprise"
              @change="getCompanyNameById"
            >
              <el-option
                v-for="item in enterpriseNameOption"
                :key="item.id"
                :label="item.fullName"
                :value="item.fullName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="事务类型" prop="transactionalType">
            <el-select
              class="input-width"
              clearable
              v-model="formModel.transactionalType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in transactionalTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="0">
          <el-form-item label="接收人" prop="receiveName">
            <el-input
              class="input-width"
              clearable
              v-model="formModel.receiveName"
              placeholder="请输入姓名"
              maxLength="64"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="通知类型" prop="noticeType">
            <el-select
              class="input-width"
              clearable
              v-model="formModel.noticeType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in noticeTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="0">
          <el-form-item label="手机号" prop="receiveNumber">
            <el-input
              clearable
              class="input-width"
              v-model="formModel.receiveNumber"
              maxLength="11"
              placeholder="请输入手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="时间范围" prop="timeRange">
            <el-time-picker
              is-range
              clearable
              format="HH:mm"
              value-format="HH:mm"
              class="input-width"
              v-model="formModel.timeRange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            >
            </el-time-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="0">
          <el-form-item label="通知内容" prop="messageContent">
            <el-input
              class="input-width"
              type="textarea"
              :autosize="{minRows: 4, maxRows: 8}"
              maxlength="500"
              show-word-limit
              v-model="formModel.messageContent"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="备注" prop="remark">
            <el-input
              class="input-width"
              type="textarea"
              :autosize="{minRows: 4, maxRows: 8}"
              maxlength="255"
              show-word-limit
              v-model="formModel.remark"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {transactionalTypeOption, noticeTypeOption} from './const'
import {
  McSmsTemplateNewSave,
  McSmsTemplateNewUpdate,
  McSmsTemplateNewGetById
} from '@const/api_messageCenter'
import {getCompanyByLikeCompanyName} from '@const/api_authCenter'
import {debounce} from '@const/utils'
export default {
  name: 'add',
  data() {
    let validatePhone = (rule, value, callback) => {
      let regExp = /^1[3456789]\d{9}$/
      if (value) {
        if (!regExp.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入手机号'))
      }
    }
    return {
      transactionalTypeOption,
      noticeTypeOption,
      enterpriseNameOption: [],
      formModel: {
        toCompanyName: '',
        toCompanyId: '',
        transactionalType: '', // 事务类型
        receiveName: '', //  接收人
        noticeType: '', //  通知类型
        receiveNumber: '',
        timeRange: null,
        messageContent: '',
        remark: ''
      },
      formRules: {
        toCompanyName: [
          {required: true, message: '请输入企业名称', trigger: 'blur'}
        ],
        transactionalType: [
          {required: true, message: '请选择事务类型', trigger: 'blur'}
        ],
        noticeType: [
          {required: true, message: '请选择通知类型', trigger: 'blur'}
        ],
        receiveNumber: [
          {required: true, validator: validatePhone, trigger: 'blur'}
        ],
        timeRange: [
          {required: true, message: '请选择时间范围', trigger: 'blur'}
        ],
        messageContent: [
          {required: true, message: '请输入通知内容', trigger: 'blur'}
        ]
      },
      noticeId: '' // 通知id
    }
  },
  created() {
    this.noticeId = this.$route.query.noticeId
    this.initLayout()
    if (this.noticeId) {
      this.getDetail()
    }
  },
  methods: {
    // 初始化右上角的保存按钮
    initLayout() {
      let obj = {
        type: 'btn',
        arr: [
          {
            val: '返回',
            icon: 'el-icon-arrow-left',
            handle: this.back
          },
          {
            type: 'primary',
            val: '保存',
            icon: 'el-icon-document-checked',
            handle: this.save
          }
        ]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    // 根据企业id 获取 企业名称
    getCompanyNameById() {
      if (!this.formModel.toCompanyName) {
        this.enterpriseNameOption = []
        return
      }
      this.formModel.toCompanyId =
        this.enterpriseNameOption.find(item => {
          return item.fullName === this.formModel.toCompanyName
        }).id || ''
    },
    // 获取企业名称
    getEnterprise(name = '') {
      this.$axios({
        method: 'get',
        url: getCompanyByLikeCompanyName,
        params: {
          companyName: name
        }
      }).then(res => {
        this.enterpriseNameOption = res.data.payload || []
      })
    },
    // 编辑时查询详情 回显数据
    getDetail() {
      this.$axios({
        url: McSmsTemplateNewGetById,
        method: 'get',
        params: {
          id: this.noticeId
        }
      }).then(res => {
        if (res.data.code === '0') {
          let payload = res.data.payload
          this.formModel = payload
          if (payload.startAt && payload.endAt) {
            this.$set(this.formModel, 'timeRange', [
              payload.startAt,
              payload.endAt
            ])
          } else {
            this.$set(this.formModel, 'timeRange', null)
          }
        }
      })
    },
    // 参数整理
    getRequestParams() {
      let params = JSON.parse(JSON.stringify(this.formModel))
      if (params.timeRange) {
        params.startAt = params.timeRange[0] || ''
        params.endAt = params.timeRange[1] || ''
      }
      if (this.noticeId) {
        params.id = this.noticeId
      } else {
        delete params.id
      }
      delete params.timeRange
      return params
    },
    saveRequest() {
      let params = this.getRequestParams()
      this.$axios({
        url: this.noticeId ? McSmsTemplateNewUpdate : McSmsTemplateNewSave,
        method: 'POST',
        data: {
          ...params
        }
      }).then(res => {
        if (res.data.code == '0') {
          let message = this.noticeId ? '更新成功' : '保存成功'
          this.$message.success(message)
          this.back()
        }
      })
    },
    // 保存操作
    save() {
      this.$refs.formModel.validate(valid => {
        if (valid) {
          debounce(this.saveRequest, 1000)()
        }
      })
    },
    // 返回操作
    back() {
      this.$router.push({
        path: '/systemSetup/smsSet'
      })
    }
  }
}
</script>

<style scoped lang="less">
.sms-add {
  padding: 0 !important;
  .notice-title {
    font-size: 16px;
    color: #26344c;
    padding: 16px;
    border-bottom: 1px solid #eef0f5;
    margin-bottom: 16px;
  }
}
.input-width {
  width: 100%;
}
</style>
